package data.connector.rippling.api.base;

import com.fasterxml.jackson.databind.JsonNode;
import data.connector.rippling.client.ClientParamsUtil;
import data.connector.rippling.client.ForwardOnlyClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.reactive.function.client.ClientResponse;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;


/**
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2020/3/25
 */
public abstract class BaseApiService extends BaseGenericService {

    protected final int SUCCESS_CODE = 200;

    protected ClientParamsUtil clientParamsUtil;
    protected ForwardOnlyClient forwardOnlyClient;

    protected Mono<MultiValueMap<String, String>> initParams(Integer tenant) {
        return this.clientParamsUtil.authQueryParams(tenant)
                .map(params -> {
                    params.set("limit", "500");
                    params.set("offset", "0");
                    return params;
                });
    }

    protected void setExceptionLog(Integer tenant, ClientResponse result, String interfaceName) {
        result.bodyToFlux(JsonNode.class).subscribe(jsonNode ->
                this.messagingTemplate.convertAndSend("data.exception.log",
                        ExceptionLog.builder().tenantId(tenant).serviceName("Rippling")
                                .interfaceName(interfaceName)
                                .status(result.rawStatusCode())
                                .msg(ObjectUtils.isEmpty(jsonNode.get("detail")) ? "" : jsonNode.get("detail").asText())
                                .logTime(LocalDateTime.now())
                                .extend(jsonNode).build()));
    }

    @Autowired
    public void setClientParamsUtil(ClientParamsUtil clientParamsUtil) {
        this.clientParamsUtil = clientParamsUtil;
    }

    @Autowired
    public void setForwardOnlyClient(ForwardOnlyClient forwardOnlyClient) {
        this.forwardOnlyClient = forwardOnlyClient;
    }
}